from selenium.webdriver import PhantomJS
import json


if __name__ == '__main__':
    url = 'http://dynamic.12306.cn/otn/board/boardMore'
    ofile = open('train_seats.jl', 'w')

    d = PhantomJS()
    d.get(url)
    header = ['出发地', '目的地', 'today', 'today+1', 'today+2', 'today+3']
    for tr in d.find_elements_by_tag_name('tr'):
        values = [td.text for td in tr.find_elements_by_tag_name('td')]
        if not values:
            continue
        values = values[:2] + [int(x) if x.isdigit() else -1 for x in values[2:]]
        record = dict(zip(header, values))
        ofile.write(json.dumps(record) + '\n')
        ofile.flush()
    ofile.close()
    d.quit()
